<?php
namespace app\home\controller;
use app\common\controller\Home;

class Collect extends Home {
    public function __construct()
    {
        parent::__construct();
        $this->CollectModel = model('User.Collect');
    }
    
    // 收藏
    public function collect() {
        if ($this->request->isAjax()) {
            $postid = $this->request->param('postid', 0);
            $userid = isset($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;

            $collect = $this->CollectModel->where(['userid' => $userid, 'postid' => $postid])->find();

            if (!$collect) {
                // 收藏
                $data = [
                    'userid' => $userid,
                    'postid' => $postid
                ];
                $res = $this->CollectModel->validate('common/User/Collect')->save($data);
                if ($res == false) {
                    $this->error('收藏失败');
                } 
                $this->success('收藏成功');
            } else {
                // 取消收藏
                $res = $this->CollectModel->destroy($collect['id'], true);
                if ($res == false) {
                    $this->error("取消收藏失败");
                } else {
                    $this->success("已取消");
                }
            }
        }
    }
}
